package me.keiwu.pub.util.wx;

import com.alibaba.fastjson.JSONObject;
import jodd.http.HttpResponse;
import me.keiwu.pub.data.RGB;
import me.keiwu.pub.data.cos.UploadResponse;
import me.keiwu.pub.util.DateUtil;
import me.keiwu.pub.util.HttpUtil;
import me.keiwu.pub.util.cos.CosUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by kei on 06/12/2017.
 */
@Component
public class WXQRCodeUtil {

    private static final Logger logger = LoggerFactory.getLogger(WXQRCodeUtil.class);
    private static final String QRCODE_REQUEST_URL_LIMIT = "https://api.weixin.qq.com/wxa/getwxacode";
    private static final String QRCODE_REQUEST_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit";

    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.secret}")
    private String secret;
    @Value("${cos.bucket.qrcode}")
    private String bucket;


    @Autowired
    private AccessTokenUtil accessTokenUtil;
    @Autowired
    private CosUtil cosUtil;


    public UploadResponse createQRCode(String sceneStr, String page, Integer width, RGB lineColor) {
        String token = accessTokenUtil.getAccessToken(appId, secret);
        String url = QRCODE_REQUEST_URL + "?access_token=" + token;

        try {
            String jsonBody = this.genParamBody(sceneStr, page, width, lineColor);
            HttpResponse resp = HttpUtil.post(url, jsonBody);
            if (resp.statusCode() == HttpStatus.OK.value()) {
                String cosPath = MessageFormat.format(
                        "/gallery/{0}-{1}.png",
                        DateUtil.formatDate(new Date(), "yyyyMMddHHmmss", Locale.ENGLISH),
                        RandomStringUtils.randomAlphanumeric(6)
                );
                UploadResponse uploadResp = cosUtil.upload(this.bucket, cosPath, resp.bodyBytes());
                uploadResp.setCosPath(cosPath);
                logger.info("request create qrcode : {}", uploadResp);
                return uploadResp;
            }
        } catch (Exception e) {
            logger.error("getAccessToken error: ", e);
        }
        return null;
    }


    private String genParamBody(String sceneStr, String page, Integer width, RGB lineColor) {
        JSONObject body = new JSONObject();
        body.put("scene", sceneStr);
        if (StringUtils.isNotBlank(page)) body.put("page", page);
        if (width != null) body.put("width", width);
        if (lineColor != null) {
            body.put("auto_color", false);
            body.put("line_color", lineColor);
        } else {
            body.put("auto_color", true);
        }
        return body.toJSONString();
    }

}
